package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 添加
     * @param dishDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        //清理Redis缓存
//        redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");
        return R.success("添加成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        //构造查询条件,过滤,排序
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(StringUtils.isNotEmpty(name), Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageInfo, lqw);

        //拷贝pageinfo
        Page<DishDto> dishDtoPage = new Page<>();
        //dishDtoPage拷贝pageinfo
        BeanUtils.copyProperties(pageInfo, dishDtoPage, "records");
        //获取pageinfo(dish)中的records
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> dtoList = new ArrayList<>();

        //遍历得到每一条记录,拷贝到dishdto
        records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //获取dish中的category_id分类id
            Long categoryId = item.getCategoryId();
            //根据id获取分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                //获取当前分类的名称,赋值给dishdto
                dishDto.setCategoryName(category.getName());
            }
            return dtoList.add(dishDto);
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(dtoList);
        return R.success(dishDtoPage);
    }

    /**
     * 查询当前菜品信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> selectOne(@PathVariable Long id) {
        DishDto dish = dishService.getByIdWithFlavor(id);
        return R.success(dish);
    }

    /**
     * 修改菜品信息
     * @param dishDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "dishCache",key = "'dish_'+#dishDto.categoryId+'_1'")
    public R<String> update(@RequestBody DishDto dishDto) {
        log.info("修改菜品"+dishDto.toString());
        dishService.update(dishDto);
        //清理Redis缓存
//        redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");
        return R.success("修改成功");
    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long>ids){
        log.info("请求删除的ids{}"+ids.toString());
        dishService.removeByCondition(ids);
        return R.success("菜品删除成功");
    }

    /**
     * 菜品展示
     * @param dish
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "dishCache",key = "'dish_'+#dish.categoryId+'_1'")
    public R<List<DishDto>> list(Dish dish){
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId()).eq(Dish::getStatus,1);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> records = dishService.list(lqw);

        //赋值dish到dishdto
        List<DishDto> dtoList = new ArrayList<>();
        records.forEach(d -> {
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(d,dishDto);
            //查询dish的口味信息
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,d.getId());
            List<DishFlavor> flavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(flavorList);
            dtoList.add(dishDto);
        });
//        redisTemplate.opsForValue().set(key,dtoList);
        return R.success(dtoList);
    }

    /**
     * 菜品状态修改
     * @param s
     * @param ids
     * @return
     */
    @PostMapping("/status/{s}")
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> status(@PathVariable String s,@RequestParam List<Long> ids){
        log.info("需要修改状态:1为启售,0为禁售;{}",s);
        log.info("接收到的id{}",ids);
        //修改菜品状态;接收1,将菜品改为启售状态status=1,接收0将菜品改为禁售状态status=0
        LambdaUpdateWrapper<Dish> lqw=new LambdaUpdateWrapper<>();
        //查找需要修改的dishid
        lqw.in(Dish::getId,ids);
        if ("1".equals(s)){
            //启售update dish set status=1
           lqw.set(Dish::getStatus,"1");
           dishService.update(lqw);
        }else{
            //禁售update dish set status=0
            //先判断是否有菜品在套餐中
            LambdaQueryWrapper<SetmealDish> lqw2=new LambdaQueryWrapper();
            lqw2.in(SetmealDish::getDishId,ids);
            int count = setmealDishService.count(lqw2);
            if (count>0){
                //当前菜品在套餐中
                throw new CustomException("当前菜品正在套餐中售卖,不能停售");
            }else{
                //允许修改
                lqw.set(Dish::getStatus,"0");
                dishService.update(lqw);
            }
        }
        return R.success("状态修改成功");
    }
}
